import React from 'react';
import '../../static/setting/index.styl'
import {Layout, Menu, Table, Icon, Button, Input, message, Popconfirm, Modal} from 'antd';
import axios from 'axios'
import AddKeyword from '../../containers/setting/addKeyword'
import Loading from '../common/Loading'

const {Sider, Content} = Layout;
const confirm = Modal.confirm;

const EditableCell = ({editable, value, onChange}) => (
  <div>
    {editable
      ? <Input style={{margin: '-5px 0'}} value={value} onChange={e => onChange(e.target.value)}/>
      : value
    }
  </div>
);

export default class Keyword extends React.Component {
  nameKeyword = ''
  eventKeyword = ''
  excludeKeyword = ''
  state = {
    selectedRowKeys: [], // Check here to configure the default column
    loaded: false,
    parentId: '',
    categorys: [],
    keywordList: [],
    pageNum: 1,
    pageSize: 10,
    moduleId: 0,
    params: {},
    ids: [],
    visible: false,
    columns: [{
      title: '关键词',
      dataIndex: 'name',
      width: '30%',
      render: (text, record) => this.renderColumns(text, record, 'name'),
    }, {
      className: 'nameKeyword',
      title: '',
      dataIndex: 'nameKeyword',
      width: '50%',
      render: (text, record) => {
        this.nameKeyword = this.renderColumns(text, record, 'nameKeyword')
        return this.renderColumns(text, record, 'nameKeyword')
      }
    }, {
      className: 'eventKeyword',
      title: '',
      dataIndex: 'eventKeyword',
      width: '50%',
      render: (text, record) => {
        this.eventKeyword = this.renderColumns(text, record, 'eventKeyword')
        return this.renderColumns(text, record, 'eventKeyword')
      }
    }, {
      className: 'excludeKeyword',
      title: '',
      dataIndex: 'excludeKeyword',
      width: '50%',
      render: (text, record) => {
        this.excludeKeyword = this.renderColumns(text, record, 'excludeKeyword')
        return this.renderColumns(text, record, 'excludeKeyword')
      }
    }, {
      title: '关键词组',
      dataIndex: 'distKeyword',
      className: 'inline',
      width: '50%',
      render: (text, record) => (
        <div className="inlineKeys">
          <div>{this.renderColumns(text, record, 'distKeyword')}</div>
          <div>{this.nameKeyword}</div>
          <div>{this.eventKeyword}</div>
          <div>{this.excludeKeyword}</div>
        </div>
      ),
    }, {
      title: '操作',
      key: 'action',
      width: '10%',
      render: (text, record) => {
        const {editable} = record;
        return (
          <div className="editable-row-operations">
            {
              editable ?
                <span>
                  <a onClick={() => this.save(record)}>保存</a>
                  <Popconfirm title="Sure to cancel?" onConfirm={() => this.cancel(record.id)}>
                    <a>取消</a>
                  </Popconfirm>
              </span> : <span onClick={() => {
                  this.edit(record.id)
                }}><Icon type="edit" style={{fontSize: '16px', marginRight: '48px'}}/></span>
            }
            <span onClick={() => {
              confirm({
                title: '提示',
                content: '确定删除吗',
                onOk: ()=>{
                  this.deleteById(record.id)
                },
              })
            }}>
            <Icon type="delete" style={{fontSize: '16px',}}/>
          </span>
          </div>
        );
      }
    }]
  };

  renderColumns = (text, record, column) => {
    return (
      <EditableCell
        style={{width: '100%'}}
        editable={record.editable}
        value={text}
        onChange={value => this.handleChange(value, record.id, column)}
      />
    );
  }

  onSelectChange = (selectedRowKeys, selectedRows) => {
    this.setState({selectedRowKeys});
    let selectedIds = selectedRows.map((item) => item.id)
    this.setState({
      id: selectedIds.toString()
    })
  }

  handleChange = (value, id, column) => {
    const newData = [...this.state.keywordList];
    const target = newData.filter(item => id === item.id)[0];
    if (target) {
      target[column] = value;
      this.setState({keywordList: newData});
    }
  }

  deleteById = (id) => {
    this.setState({
      id: id
    }, () => {
      this.onDelete()
    })
    message.success('删除成功');
  }

  onDelete = async () => {
    if(!this.state.id){
      message.error('请至少选择一条数据!')
      return
    }
    let res = await
      axios.post('vrv-monitor-platform-web/moniterkey/delete', {
        ids: this.state.id
      })
    if (res.data.statusCode === 200) {
      this.getKeyword()
    } else {
      message.error(res.data.message);
    }
  }

  //编辑
  edit = async (id) => {
    const newData = [...this.props.keywordList];
    const target = newData.filter(item => id === item.id)[0];
    if (target) {
      target.editable = true;
      this.setState({keywordList: newData});
    }
  }

  //保存修改
  save = async (item) => {
    let res = await
      axios.post('vrv-monitor-platform-web/moniterkey/update', {
        id: item.id,
        name: item.name,
        distKeyword: item.distKeyword,
        nameKeyword: item.nameKeyword,
        eventKeyword: item.eventKeyword,
        excludeKeyword: item.excludeKeyword,
      })
    if (res.data.statusCode === 200) {
      this.getKeyword()
    } else {
      message.error(res.data.message);
    }
  }

  //取消
  cancel = () => {
    this.getKeyword()
  }

  //获取分类
  queryCategory = async () => {
    let res = await
      axios.get('vrv-monitor-platform-web/category/query')
    if (res.data.statusCode === 200) {
      this.setModuleId(res.data.data[0].id)
      this.setState({
        categorys: res.data.data
      })
    } else {
      message.error(res.data.message)
    }
  }

  setModuleId = (id) => {
    this.setState({
      moduleId: id
    }, () => {
      this.getKeyword()
    });
  }

  //根据categoryId获取关键词
  getKeyword = () => {
    this.setState({
      loaded: false,
      selectedRowKeys: []
    })
    let params = {
      parentId: this.state.moduleId,
      pageNum: this.state.pageNum,
      pageSize: this.state.pageSize
    }
    this.props.settingActions.fetchKeywordlist(params);
    this.setState({
      keywordList: this.props.keywordList,
      loaded: true
    })
  }

  //分类改变
  onChange = (pagination) => {
    this.queryTodayOpinion(pagination.current, pagination.pageSize)
  }

  hideModal = () => {
    this.setState({
      visible: false
    })
  }

  showModal = () => {
    this.setState({
      visible: true
    })
  }

  componentDidMount() {
    this.queryCategory()
  }

  render() {
    const {selectedRowKeys} = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
    };
    return (
      <div className="keyword">
        <Layout style={{height: '80%'}}>
          <Sider
            style={{background: '#fff', borderRight: '1px solid #e6e9ed'}}>
            {
              this.state.categorys.length > 0 ?
                <Menu mode="inline" style={{height: '100%', borderRight: 0}} defaultSelectedKeys={['0']}>
                  {
                    this.state.categorys.map((item, i) => {
                      return <Menu.Item key={i} style={{height: '50px', lineHight: '50px'}}>
                        <span style={{position: 'absolute', height: '100%', width: '100%'}} onClick={() => {
                          this.setModuleId(item.id)
                        }}>{item.categoryName}</span>
                      </Menu.Item>
                    })
                  }
                </Menu> : <div>暂无分类</div>
            }
          </Sider>
          <Layout>
            <div className="table-operations">
              <div className="button">
                <Button onClick={()=>{
                  confirm({
                    title: '提示',
                    content: '确定删除吗',
                    onOk: () => {
                      this.onDelete();
                    },
                  })
                }}>删除</Button>
                <Button onClick={this.showModal}>添加</Button>
              </div>
            </div>
            <Content style={{margin: '0', padding: 0, background: '#fff', minHeight: 280}}>
              {
                this.state.loaded ?
                  <Table bordered rowSelection={rowSelection} columns={this.state.columns}
                         dataSource={this.props.keywordList}
                         onChange={this.onChange} rowKey="id" /> : <Loading/>
              }
              {
                this.state.visible ?
                  <AddKeyword parentId={this.state.moduleId} onHide={this.hideModal}/> : ''
              }
            </Content>
          </Layout>
        </Layout>
      </div>
    );
  }
}